<template>
  <div>
      <el-main>
          <!-- 搜索框区 -->
      <div>
        <el-input
          style="width: 180px; height: 32px; margin-right: 5px"
          placeholder="请输入id"
          v-model="selectByKey.id"
          suffix-icon="Search"
          clearable
        >
        </el-input>
        <!-- <el-input disabled
          style="width: 180px; height: 32px; margin-right: 5px"
          placeholder="请输入用户名"
          v-model="selectByKey.username"
          suffix-icon="Search"
          clearable
        >
        </el-input> -->
        <el-input
          style="width: 180px; height: 32px; margin-right: 5px"
          placeholder="请输入电话"
          suffix-icon="Message"
          v-model="selectByKey.phone"
          clearable
        >
        </el-input>
        <el-button type="primary"
          style="height: 32px; width: 60px; font-size: 13px" @click="roomInfoByPhone">搜索</el-button>
          <el-button type="warning"
          style="height: 32px; width: 60px; font-size: 13px" @click="reset">重置</el-button>
      </div>

      <!-- 新增按钮区域 -->
      <div style="margin: 10px 0px">
        <!-- <el-button disabled @click="handleAdd" type="primary">
          新增<el-icon class="el-icon--right"><CirclePlus /></el-icon>
        </el-button> -->

        <!-- <el-popconfirm
                width="220"
                confirm-button-text="确定"
                cancel-button-text="不,再想想"
                title="您确定要删除吗?"
                @confirm="delBatch"
              >
                <template #reference>
                 <el-button disabled type="danger">
                  批量删除<el-icon class="el-icon--right"><Remove /></el-icon>
                </el-button>
                </template>
              </el-popconfirm> -->

        <!-- <el-upload
            class="upload-demo"
            :action="'http://'+serverIp+':9090/user/import'"
            style="display: inline-block;margin: 0px 12px;"
            :show-file-list="false"
            accept="xlsx"
            :on-success="handleImportSuccess"
            :on-error="handleImportError"
            >
             <el-button disabled type="primary">
                导入<el-icon class="el-icon--right"><Upload /></el-icon>
             </el-button>
        </el-upload> -->
       


        <!-- <el-button disabled type="primary" @click="handleExport">
          导出<el-icon class="el-icon--right"><Download /></el-icon>
        </el-button> -->
      </div>

      <div style="margin-top: 30px;">
        <el-scrollbar>
          <el-table
            height="450"
            :data="tableData"
            border
            stripe
            size="small"
            :header-cell-class-name="headerBg"
            @selection-change="handleSelectionChange"
          >
           <el-table-column type="selection" width="55" />
            <!-- <el-table-column prop="openid" label="openid" width="70" /> -->
            <!-- <el-table-column prop="merchantIid" label="商家Id" width="70" /> -->
            <!-- <el-table-column prop="roomId" label="房间id" width="70" /> -->
            <el-table-column prop="id" label="订单id" width="170" />
            <el-table-column prop="createTime" label="创建时间" width="170" />
            <!-- <el-table-column prop="role" label="角色" width="250">
              <template #default="scope">
                <el-tag type="primary" v-if="scope.row.role === 'ROLE_ADMIN'">管理员</el-tag>
                <el-tag type="warning" v-if="scope.row.role === 'ROLE_TEACHER'">老师</el-tag>
                <el-tag type="success" v-if="scope.row.role === 'ROLE_STUDENT'">学生</el-tag>
              </template>
            </el-table-column> -->
            <el-table-column prop="startTime" label="开始时间" width="170" />
            <el-table-column prop="overtime" label="加时" width="70" />
            <el-table-column prop="endTime" label="结束时间" width="170" />
            <el-table-column prop="sumPrice" label="总价" width="70" />
            <el-table-column prop="state" label="订单状态" width="90" >
              <template #default="scope">
                <el-tag v-if="scope.row.state === '已完成'" type="success">{{scope.row.state}}</el-tag>
                <el-tag v-if="scope.row.state === '待支付'" type="warning">{{scope.row.state}}</el-tag>
                <el-tag v-if="scope.row.state === '消费中'" type="">{{scope.row.state}}</el-tag>
                <el-tag v-if="scope.row.state === '已取消'" type="info">{{scope.row.state}}</el-tag>
                <el-tag v-if="scope.row.state === '待消费'" type="info">{{scope.row.state}}</el-tag>
                <el-tag v-if="scope.row.state === '已支付'" type="danger">{{scope.row.state}}</el-tag>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="操作" label="edit" >
              <el-button type="success">编辑 </el-button>
              <el-button type="danger">删除</el-button>
            </el-table-column> -->
            <el-table-column prop="edit" label="操作">
              <template #default="scope">
                <el-button
                type="success"
                  @click="handleEdit(scope.$index, scope.row)"><el-icon style="margin-left:3px"><EditPen /></el-icon>
                  </el-button>
                <el-popconfirm
                width="220"
                confirm-button-text="确定"
                cancel-button-text="不,再想想"
                title="您确定要删除吗?"
                @confirm="handleDelete(scope.$index, scope.row.id)"
              >
                <template #reference>
                  <el-button disabled type="danger"><el-icon style="margin-left:3px"><Delete /></el-icon>
                  </el-button>
                </template>
              </el-popconfirm>
              <!-- 详情按钮 -->
              <el-button @click="handleInfo(scope.$index, scope.row)" type="info"><el-icon style="margin-left:3px"><InfoFilled /></el-icon></el-button>

              </template>
            </el-table-column>
          </el-table>
          <!-- 分页器 -->
          <div style="margin: 10px">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageNum"
              :page-sizes="[2,5,10,15]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
            >
            </el-pagination>
          </div>
        </el-scrollbar>

        <!-- 对话框 -->
         <el-dialog :before-close="handleClose" :close-on-click-modal="false" title="订单信息" v-model="dialogFormVisible" width="30%" >
          <el-form label-width="80px" size="small">
             <el-form-item label="订单号">
              <el-input disabled v-model="form.id" autocomplete="off"></el-input>
            </el-form-item>
             
            <el-form-item label="创建时间">
              <el-input disabled v-model="form.createTime" autocomplete="off"></el-input>
            </el-form-item>
            <!-- <el-form-item label="角色">
              <el-select clearable v-model="form.role" placeholder="请选择角色" style="width: 100%">
                <el-option v-for="item in roles" :key="item.name" :label="item.name" :value="item.flag"></el-option>
              </el-select>
            </el-form-item> -->
            
            <el-form-item label="开始时间">
              <el-input disabled v-model="form.startTime" autocomplete="off"></el-input>
              <!-- <el-date-picker
                  v-model="form.startTime"
                  type="datetime"
                  placeholder="Pick a Date"
                  format="YYYY-MM-DD hh:mm:ss"
                  value-format="YYYY-MM-DD hh:mm:ss"
                /> -->
            </el-form-item>
            <el-form-item label="加时">
              <el-input style="width: 84px;" v-model="form.overtime" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="结束时间">
              <el-input disabled v-model="form.endTime" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item  label="空调增加时长">
              <el-input style="width: 84px;" v-model="form.conditionTime" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="总价">
              <el-input disabled v-model="form.sumPrice" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="form.state" placeholder="请选择订单状态" style="width: 100%">
                <el-option  label="已完成" value="已完成">
                  <el-tag type="success">已完成</el-tag>
                </el-option>
                <el-option  label="已取消" value="已取消">
                    <el-tag type="info">已取消</el-tag>
                </el-option>
                <el-option  label="已支付" value="已支付">
                    <el-tag type="danger">已支付</el-tag>
                </el-option>
                <el-option  label="待支付" value="待支付">
                    <el-tag type="warning">待支付</el-tag>
                </el-option>
                <el-option  label="待消费" value="待消费">
                    <el-tag type="info">待消费</el-tag>
                </el-option>
                <el-option  label="消费中" value="消费中">
                    <el-tag type="">消费中</el-tag>
                </el-option>
              </el-select>
          
            </el-form-item>
            <!-- <el-form-item label="用户id">
              <el-input disabled v-model="form.userId" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="商家id">
              <el-input disabled v-model="form.merchantId" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="房间id">
              <el-input disabled v-model="form.roomId" autocomplete="off"></el-input>
            </el-form-item> -->
          </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="save">
                  确定
                </el-button>
              </span>
            </template>
        </el-dialog>

        <!-- 抽屉 -->
        <el-drawer
            ref="drawerRef"
            v-model="drawer"
            title="订单详情"
            direction="rtl"
            :before-close="()=>{this.drawer = false,this.form = {}}"
          >
            <div>
                  <el-descriptions
                    title="订单信息"
                    :column="1"
                    size="default"
                    direction="horizontal"
                    style="margin:0px 0px 10px 0px"
                  >
                    <el-descriptions-item label="订单id：">{{form.id}}</el-descriptions-item>
                    <el-descriptions-item label="创建时间：">{{form.createTime}}</el-descriptions-item>
                    <el-descriptions-item label="开始时间：">{{form.startTime}}</el-descriptions-item>
                    <el-descriptions-item label="加时：" >{{form.overtime}}</el-descriptions-item>
                    <el-descriptions-item label="结束时间：" >{{form.endTime}}</el-descriptions-item>
                    <el-descriptions-item label="空调总时长：" >{{form.conditionTime}}</el-descriptions-item>
                    <el-descriptions-item label="总价：" >{{form.sumPrice}}</el-descriptions-item>
                    <el-descriptions-item label="状态：" >
                      <el-tag :type="state" size="small">
                        {{form.state}}
                      </el-tag>
                    </el-descriptions-item>
                  </el-descriptions>

                  <el-descriptions
                    title="棋牌室信息"
                    :column="1"
                    size="default"
                    direction="horizontal"
                    style="margin:10px 0px"
                  >
                    <el-descriptions-item label="房间id：">{{roomForm.id}}</el-descriptions-item>
                    <el-descriptions-item label="类型："><el-tag size="small">{{roomForm.type}}</el-tag></el-descriptions-item>
                    <el-descriptions-item label="价格：">{{roomForm.price}}</el-descriptions-item>
                    <el-descriptions-item label="当前预约状态：" ><el-tag :type="roomForm.reservationState?'warning':'success'" size="small">{{roomForm.reservationState?"未预约":"已预约"}}</el-tag></el-descriptions-item>
                    <el-descriptions-item label="解锁状态：" ><el-tag :type="roomForm.lockState?'warning':'success'" size="small">{{roomForm.lockState?"未解锁":"已解锁"}}</el-tag></el-descriptions-item>
                  </el-descriptions>

                  <el-descriptions
                    title="用户信息"
                    :column="1"
                    size="default"
                    direction="horizontal"
                  >
                    <el-descriptions-item label="用户名：">{{userForm.username}}</el-descriptions-item>
                    <el-descriptions-item label="电话：">{{userForm.phone}}</el-descriptions-item>
                  </el-descriptions>
            </div>
          </el-drawer>

       </div>
    </el-main>
      
    
  </div>
</template>

<script>
import { mapState } from 'vuex'
import {serverIp} from '../../public/config.js'

export default {
    name:'order',
    data(){
        return{
          serverIp:serverIp,
          // 详情
          drawer:false,
          dialogForm:{},
          //user信息
          userForm:{
            username:"",
            phone:""
          },
          //棋牌室信息
          roomForm:{},
          //
          tableData:[],

            //user
            pageNum:1,
            pageSize:10,
            total:0,
            selectByKey:{
                merchantId:"",
                id:"",
                phone:""
            },
            //编辑表单
            form:{},
            roles:[],
            dialogFormVisible: false,
            // 多选框选中对象
            multipleSelection:[],
        }
    },
    created(){
        //
        this.load()
        //

    },
    methods:{
      //详情按钮
        handleInfo(index,row){
          //console.log('row',row.openid);
            //发送请求
            this.userInfoByOpenid(row.openid)
            //console.log(this.userForm);
            this.roomInfoByRoomId(row.roomId)

            //
            this.drawer = true
            this.form = row
        },
        //导出成功
        handleExport(){
            window.open(`http://${serverIp}:9090/user/export`)
        },
        //导入失败
        handleImportError(){
             this.$message.error("导入失败!")
        },
        //导入成功
        handleImportSuccess(){
            this.$message.success("导入成功!")
            this.load()
        },
         //多选删除
        delBatch(){
        let ids = this.multipleSelection.map(v => v.id)  //[{},{},{}] => [1,2,3]
        this.request.post("/user/del/batch",ids).then(res => {
            if (res.code === '200') {
            this.$message.success("删除成功")
            this.load()
            } else {
            this.$message.error("删除失败")
            }
        })
        },
        //多选选中的对象
        handleSelectionChange(val){
        this.multipleSelection = val
        },
        //对话框关闭
        handleClose(){
          //console.log('@@@@');
        this.dialogFormVisible = false,
        this.form = {}
        this.reset()
        },
    
        //删除行
        handleDelete(index,id){
        this.request.delete("/user/"+ id).then(res => {
            if (res.code === '200') {
            this.$message.success("删除成功")
            this.load()
            } else {
            this.$message.error("删除失败")
            }
        })
        },
        //编辑
        handleEdit(index, row){
        //console.log(index, row);
        this.dialogFormVisible = true,
        this.form = row
        //空调增加时长默认为0
        this.form.conditionTime = 0
        //订单增加时长默认为0
        this.form.overtime = 0
        },
        //保存表单
        save() {
              //编辑订单接口
              // this.request.put("/update/startTime", this.form).then(res => {
              //   //console.log('update',res);
              //     if (res.code === '200') {
              //     this.$message.success("保存成功")
              //     } else {
              //     this.$message.error("保存失败")
              //     }
              // })
              // 编辑订单加时时长
                //准备JSON
                let O = {
                id:this.form.id,
                overtime:this.form.overtime,
                // 不变就默认为零，非否则必须填写增加的时长
                conditionTime:this.form.conditionTime
              }
              //console.log('overtime1',O);
              this.request.put("/order/update/overtime", JSON.stringify(O)).then(res => {
                console.log('overtime',res);
                  if (res.code === 200) {
                  this.$message.success("更新成功")
                  } else {
                  this.$message.error("更新失败")
                  }
              })
              
              

              //编辑订单状态
              //准备JSON
              let S = {
                id:this.form.id,
                state:this.form.state
              }
              this.request.put("/order/update/state", JSON.stringify(S)).then(res => {
                // console.log('state',res);
                  if (res.code === 200) {
                  this.$message.success("更新成功")
                  //最后统一处理
                  this.dialogFormVisible = false
                  this.form = {}
                  this.load()
                  } else {
                  this.$message.error("更新失败")
                  }
              })

              
        },

        //新增按钮
        handleAdd(){
        this.dialogFormVisible = true;
        },
        // 表头背景
        headerBg({ row, rowIndex }) {
        if (rowIndex == 0) {
            return "headerBgClass";
        }
        },

        // 重置按钮
        reset(){
        this.selectByKey={},
        this.load()
        },

        //发送请求
        load() {
          // 准备JSON
          // 默认商家个人id  订单id查询
            let json = {merchantId:this.mUser.id,id:this.selectByKey.id}
            this.request.post("/order/getAll/"+this.pageNum+"/"+this.pageSize, JSON.stringify(json)
            ).then(res => {
                if(res.code === 200){
//console.log(res)
                this.tableData = res.data.records
                this.total = res.data.total
                }
                
            })

            //
          



        },
        //根据电话查询
        roomInfoByPhone(){
          if (this.selectByKey.phone === "" || this.selectByKey.phone === undefined) {
            this.load()
            return
          }
            //准备Json对象
            let f =  {
                username:"",
                phone:this.selectByKey.phone,
                id:""
              }
              this.request.post("/user/getAll/"+this.pageNum+"/"+this.pageSize,JSON.stringify(f)
              // {
              //     params: {
              //     username: this.username,
              //     email: this.email,
              //     address:this.address
              //     }
              // }
              ).then(res => {
                  if(res.code === 200){
                // 查询到相关用户信息
                  //console.log("phone",res)
                  let newObj =[]
                  res.data.records.forEach(item => {
                      this.tableData.forEach(i=>{
                          if (item.openid === i.openid) {
                            newObj.push(i)
                            return
                          }
                      })
                  })
                  this.tableData = newObj
                  this.total = newObj.length

                  }
                  


              })
        },
        

        ////根据id查询棋牌室信息
        roomInfoByRoomId(roomId){
          //console.log('roomId',roomId);
          // 默认商家id为1
            this.request.get("/room/getById/"+roomId+"/"+this.mUser.id+"").then(res=>{
              //console.log('room',res);
              if(res.code === 200){
                this.roomForm = res.data
                return
              }
            })
        },





        // 根据openid查询用户信息
        userInfoByOpenid(openId){
            //获取用户信息byId
            //准备JSON
            let S = {
                username:"",
                phone:"",
                id:""
            }
           this.request.post("/user/getAll/1/20000",JSON.stringify(S)).then(res => {
              if(res.code === 200){
                  //筛选出该openid的user
                  res.data.records.forEach(item => {
                      if(item.openid === openId){
                          this.userForm = item
                          return
                      }
                  });
              }
              
            // this.roles = res.data
          })
        },

        // 分页器
        handleSizeChange(val) {
        //console.log(`每页 ${val} 条`);
        this.pageSize = val;
        this.load();

        },
        handleCurrentChange(val) {
        //console.log(`当前页: ${val}`);
        this.pageNum = val;
        this.load();
        },
    },
    computed:{
      // 计算支付状态标签
      state(){
        if (this.form.state === "已完成") {
          return "success"
        }else if(this.form.state === "待支付"){
          return "warning"
        }else if(this.form.state === "消费中"){
          return ""
        }else if(this.form.state === "已取消"){
          return "info"
        }else if(this.form.state === "待消费"){
          return "info"
        }else if(this.form.state === "已支付"){
          return "danger"
        }
        
      },
      ...mapState("personAbout",["mUser"])
    }

}
</script>

<style>
.headerBgClass {
  background-color: rgb(221, 213, 213) !important;
}
</style>